$(function() {
	var key = getcookie('doutingshop');
	var ifcart = GetQueryString('ifcart');
	if(ifcart==1){
		var cart_id = GetQueryString('cart_id');
		var data = {key:key,ifcart:1,cart_id:cart_id};
	}else{
		var goods_id = GetQueryString("goods_id");
		var number = GetQueryString("buynum");
		var cart_id = goods_id+'|'+number;
		var data = {key:key,cart_id:cart_id};
	}

    var isFCode = false;

    var pf = function(f) {
        return parseFloat(f) || 0;
    };

    var p2f = function(f) {
        return (parseFloat(f) || 0).toFixed(2);
    };

    var isEmpty = function(o) {
        var b = true;
        $.each(o, function(k, v) {
            b = false;
            return false;
        });
        return b;
    }

    var cod = (function() {
        // COD开关
        var codSwitch = $('#buy-type-offline').prop('checked');

        // COD状态
        var codGlobal = false;
        var codStores = {};

        // 0b1 正在使用货到付款
        // 0b2 可以使用预存款和充值卡
        var paymentFlag = 2;

        var stateChanged = function() {
            if (codGlobal) {
                var flag1 = false;
                var flag2 = false;

                $('.store-cod-supported').each(function() {
                    if (codStores[$(this).data('store_id')]) {
                        $(this).hide();
                        flag1 = flag1 || true;
                    } else {
                        $(this).show();
                        flag2 = flag2 || true;
                    }
                });

                paymentFlag = 0;

                if (flag1) {
                    paymentFlag |= 1;
                }
                if (flag2) {
                    paymentFlag |= 2;
                }
            } else {
                $('.store-cod-supported').hide();

                paymentFlag = 2;
            }

            switch (paymentFlag) {
            case 1:
                // 支持货到付款的同时不支持在线支付
                $('#offline').show();
                $('#deposit').hide();
                break;

            case 3:
                // 支持货到付款的同时支持在线支付
                $('#offline').show();
                $('#deposit').show();
                break;

            case 0:
                // none
            case 2:
                // 只支持在线支付
            default:
                // default
                $('#buy-type-offline').prop('checked', false);
                $('#buy-type-online').prop('checked', true);

                // 关闭COD开关
                codSwitch = false;

                $('#offline').hide();
                $('#deposit').show();
                break;
            }

            // 在线支付默认优先开关控制
            if (!codSwitch) {
                $('#deposit').show();
            }

            refleshTotals();
        };

        var refleshTotals = function() {
            if (codSwitch && codGlobal) {
                var codTotal = 0;
                var onlineTotal = 0;

                $('.store_total').each(function() {
                    var sid = this.id.substring(2);
                    var st = parseFloat(this.innerHTML) || 0;
                    if (codStores[sid]) {
                        codTotal += st;
                    } else {
                        onlineTotal += st;
                    }
                });

                //console.log(codTotal);
                //console.log(onlineTotal);
                $('#online-total-wrapper').show();
                $('#online-total').html(p2f(onlineTotal));
            } else {
                $('#online-total-wrapper').hide();
            }
        }

        var switchTriggered = function(b) {
            codSwitch = b;

            stateChanged();
        };

        var stateUpdateded = function(allow_offpay, allow_offpay_batch) {
            codGlobal = allow_offpay == '1';
            codStores = allow_offpay_batch || {};

            stateChanged();
        };

        return {
            switchTriggered: switchTriggered,
            stateUpdateded: stateUpdateded,
            refleshTotals: refleshTotals,
            z: 0
        };
    })();


	$.ajax({//提交订单信息
		type:'post',
		url:ApiUrl+'/user/eb/findOrderById/'+cart_id,
		dataType:'json',
		success:function(result){
            // console.log(result)
            checklogin(result.rspCode);
			var data = result.order;
			if(typeof(data)=='undefined'){
				location.href = WapSiteUrl;
			}

			var htmldata = '';
			var total_price = 0;
			var i = 0;
			var j = 0;

            if(data.advanceMoney)
            {
                if(data.state == 101)
                {
                    total_price = data.price - data.advanceMoney;
                }
                else if(data.state == 0)
                {
                    total_price = data.advanceMoney;
                }
            }
            else
                total_price=data.price;
			$('#total_price').html(total_price);
			$('input[name=total_price]').val(total_price);

            // 选择COD则不显示预存款和充值卡
            cod.switchTriggered(0);
            $('#online').click(function() {
                cod.switchTriggered(0);
            });
            $('#offline').click(function() {
                cod.switchTriggered(1);
            });

            //清单
            data.WapSiteUrl = WapSiteUrl;
            var html = template.render('cart-list', data);
            $("#goods-list").html(html);


			// if(data.ifshow_offpay){//支付方式
			// 	$('#offline').show();
			// }else{
			// 	$('#offline').hide();
			// }

			$('select[name=voucher]').change(function(){//选择代金券
				var store_id = $(this).attr('store_id');
				var varr = $(this).val();
				if(varr == 0){
					var store_price = 0;
				}else{
					var store_price = pf(varr.split('|')[2]);
				}
				var store_total_price = pf($('#st'+store_id).attr('store_price'));
				var store_tran = pf($('#store'+store_id).html());
				store_total = pf(store_total_price) - store_price + store_tran;
				$("#sv"+store_id).html(p2f(store_price));
				$("#st"+store_id).html(p2f(store_total));

				var total_price = 0;
				$('.store_total').each(function(){
					total_price += pf($(this).html());
				});
				$('#total_price').html(p2f(total_price));

                cod.refleshTotals();
			});
		}
	});

	//获取默认收货地址
    $.ajax({
    	type:'post',
    	url:ApiUrl+'/user/eb/getDeliveryAddressPage',
    	dataType:'json',
    	data:{'defaultAddress':1},
    	success:function(result){
            // console.log(result);
            checklogin(result.rspCode);
            if (result.rspCode==0&&result.total>0) {
            	var address = result.rows[0];
                $('#true_name').html(address.consignee);
				$('#address').html(address.addProvince+' '+address.addCity+' '+address.addDistrict+' '+address.address);
				$('#mob_phone').html(address.phone);
                $('input[name=address_id]').val(address.id);
            }else{
            	var thisPrarent = $(".buys1-address-cnt");
                hideDetail(thisPrarent);
            }
    	}
    });
    // 点击使用新地址才显示新地址编辑框
    $('#new-address-button').click(function() {
        $('#new-address-wrapper').show();
        $("#city-select").citySelect({required:false});
    });
    $(".buys1-edit-address").click(function(){//修改收获地址
        var self = this;
        $.ajax({
        	type:'post',
            url:ApiUrl+'/user/eb/getDeliveryAddressPage',
            dataType:'json',
        	success:function(result){
                console.log(result);
                checklogin(result.rspCode);
        		var data = result.rows;
        		var html = '';
        		for(var i=0;i<data.length;i++){
        			html+='<li class="existent-address">'
			                    +'<label>';
                    if (data[i].defaultAddress==1) {
                        html+='<input type="radio" name="address" checked class="rdo address-radio" value="'+data[i].id+'" />'
                    } else {
                        html+='<input type="radio" name="address" class="rdo address-radio" value="'+data[i].id+'" />'
                    }
                    html+='<span class="mr5 rdo-span"><span class="true_name_'+data[i].id+'">'+data[i].addProvince+'</span> <span class="address_id_">'+data[i].addDistrict+' '+' '+data[i].addCity+data[i].address+'</span> <span class="mob_phone_'+data[i].phone+'">'+data[i].phone+'</span></span>'
	                    +'</label>'
	                    +'<a class="del-address" href="javascript:void(0);" address_id="'+data[i].id+'">[删除]</a>'
            		+'</li>';
        		}
        		$('li.existent-address').remove();
        		$('#addresslist').before(html);

                // 点击已有地址 隐藏新地址输入框
                $('li.existent-address input').click(function() {
                    $('#new-address-wrapper').hide();
                    $('.error-tips').hide();
                });

        		$('.del-address').click(function(){
                    var $this = $(this);
        			var address_id = $(this).attr('address_id');
        			$.ajax({
        				type:'post',
        				url:ApiUrl+'/user/eb/deleteDeliveryAddress/'+address_id,
        				dataType:'json',
        				success:function(result){
                            checklogin(result.rspCode);
                            if (result.rspCode==0) {
                                $this.parent('li').remove();
                            };
        					
        				}
        			});
        		});

                $('input[name=address]').click(function() {
                    var city_id = $(this).attr('city_id');
                    var area_id = $(this).attr('area_id');

                    $('input[name=city_id]').val(city_id);
                    $('input[name=area_id]').val(area_id);
                });
        	}
        });
        var thisPrarent = $(this).parents(".buys1-address-cnt");
        hideDetail(thisPrarent);
    });

	$.sValid.init({//地址验证
        rules:{
        	vtrue_name:"required",
        	vmob_phone:"required",
            vprov:"required",
            vcity:"required",
            vregion:"required",
            vaddress:"required",
        },
        messages:{
        	vtrue_name:"姓名必填！",
        	vmob_phone:"手机号必填！",
            vprov:"省份必填！",
            vcity:"城市必填！",
            vregion:"区县必填！",
            vaddress:"街道必填！",
        },
        callback:function (eId,eMsg,eRules){
            if(eId.length >0){
                var errorHtml = "";
                $.map(eMsg,function (idx,item){
                    errorHtml += "<p>"+idx+"</p>";
                });
                $(".error-tips").html(errorHtml).show();
            }else{
                 $(".error-tips").html("").hide();
            }
        }
    });

    $(".save-address").click(function (){//更换收获地址
        var self = this;
        var ele = $(this);
        var selfPr;
        //获取address_id
        var addressRadio = $('.address-radio');
        var address_id = '';
        for(var i =0;i<addressRadio.length;i++){
            if(addressRadio[i].checked){
                address_id = addressRadio[i].value;
            }
        }
        if(address_id!=''&&address_id!=0){//变更地址
        	$.ajax({
        		type:'post',
        		url:ApiUrl+'/user/eb/defaultDeliveryAddress/'+address_id,
        		dataType:'json',
        		success:function(result){
                    checklogin(result.rspCode);
        			if(result.rspCode==0){
                        var thisPrarent = ele.parents(".buys1-address-cnt");
                            showDetial(thisPrarent);
                        $.ajax({
                            type:'post',
                            url:ApiUrl+'/user/eb/getDeliveryAddressPage',
                            dataType:'json',
                            data:{'defaultAddress':1},
                            success:function(result){
                                if (result.rspCode==0&&result.total>0) {
                                    var address = result.rows[0];
                                    $('#true_name').html(address.consignee);
                                    $('#address').html(address.addProvince+' '+address.addCity+' '+address.addDistrict+' '+address.address);
                                    $('#mob_phone').html(address.phone);
                                    $('input[name=address_id]').val(address.id);
                                    $('input[name=area_id]').val(address.addDistrict);
                                    $('input[name=city_id]').val(address.addCity);
                                }
                            }
                        });
                    }
                    // cod.stateUpdateded(result.datas.allow_offpay, result.datas.allow_offpay_batch);

                    // $('input[name=allow_offpay]').val(result.datas.allow_offpay);
                    // $('input[name=offpay_hash]').val(result.datas.offpay_hash);
                    // $('input[name=offpay_hash_batch]').val(result.datas.offpay_hash_batch);

        			return false;
        		}
        	});
        }else{//保存地址
			if($.sValid()){
				var true_name = $('input[name=true_name]').val();
				var mob_phone = $('input[name=mob_phone]').val();
				// var tel_phone = $('input[name=tel_phone]').val();
				var province = $('select[name=prov]').val();
				var city_id = $('select[name=city]').val();
				var area_id = $('select[name=region]').val();
				var address = $('input[name=vaddress]').val();

				var DeliveryAddress = {
					consignee:true_name,
					phone:mob_phone,
					addProvince:province,
					addCity:city_id,
					addDistrict:area_id,
					address:address,
					defaultAddress:1
				};

				//ajax 提交收货地址
				$.ajax({
					type:'post',
					url:ApiUrl+'/user/eb/addDeliveryAddress',
					contentType: "application/json",
                    data: JSON.stringify(DeliveryAddress),
					dataType:'json',
					success:function(result){
                        checklogin(result.rspCode);
						if(result.rspCode==0){
                            var thisPrarent = ele.parents(".buys1-address-cnt");
                            showDetial(thisPrarent);
							$.ajax({
						    	type:'post',
						    	url:ApiUrl+'/user/eb/getDeliveryAddressPage',
						    	dataType:'json',
						    	data:{'defaultAddress':1},
						    	success:function(result){
						            if (result.rspCode==0&&result.total>0) {
						            	var address = result.rows[0];
						                $('#true_name').html(address.consignee);
										$('#address').html(address.addProvince+' '+address.addCity+' '+address.addDistrict+' '+address.address);
										$('#mob_phone').html(address.phone);
						            	$('input[name=address_id]').val(address.id);
										$('input[name=area_id]').val(address.addDistrict);
										$('input[name=city_id]').val(address.addCity);
						            }
						    	}
						    });
						}
					}
				});
			}else{
				return false;
			}
        }
    });
    $('#pguse').click(function(){//验证密码
    	var loginpassword = $("input[name=loginpassword]").val();
    	if(loginpassword == ''){
    		$('.password_error_tip').show();
    		$('.password_error_tip').html('支付密码不能为空');
    		return false;
    	}
    	$.ajax({
    		type:'post',
    		url:ApiUrl+'/index.php?act=member_buy&op=check_password',
    		data:{key:key,password:loginpassword},
    		dataType:'json',
    		success:function(result){
                checklogin(result.rspCode);
    			if(result.datas == 1){
    				$('input[name=passwd_verify]').val('1');
    				$('#pd').hide();
    			}else{
    				$('#pd').show();
    				$('.password_error_tip').show();
    				$('.password_error_tip').html(result.datas.error);
    			}
    		}
    	});
    });

    $('#usepdpy,#usercbpay').click(function(){//验证密码切换
    	if($('#usepdpy').attr('checked') || $('#usercbpay').attr('checked')){
    		$('#pd').show();
    	}else{
    		$('#pd').hide();
    	}
    });


    $('#buy_step2').click(function(){//提交订单step2
    	var data = {};
    	data.orderId = cart_id;

    	var address_id = $('input[name=address_id]').val();
    	data.addressId = address_id;
        $.ajax({
        	type:'post',
        	url:ApiUrl+'/user/eb/orderBoundDeliveryAddress',
        	data:data,
        	dataType:'json',
        	success:function(result){
                checklogin(result.rspCode);
                if (result.rspCode!=0) {
                    $.sDialog({
                        skin:"red",
                        content:result.rspDesc,
                        okBtn:false,
                        cancelBtn:false
                    });
                    return false;
                }
        		
                location.href = WapSiteUrl+'/tmpl/member/order_list.html';
        		return false;
        	}
        });
    });

    function showDetial(parent){
        $(parent).find(".buys1-edit-btn").show();
        $(parent).find(".buys1-hide-list").addClass("hide");
        $(parent).find(".buys1-hide-detail").removeClass("hide");
    }
    function hideDetail(parent){
        $(parent).find(".buys1-edit-btn").hide();
        $(parent).find(".buys1-hide-list").removeClass("hide");
        $(parent).find(".buys1-hide-detail").addClass("hide");
    }
});